package com.backwaveweibo.bww.service.impl;

import com.backwaveweibo.bww.entity.Comments;
import com.backwaveweibo.bww.mapper.CommentsMapper;
import com.backwaveweibo.bww.service.CommentsService;
import com.backwaveweibo.bww.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author GHW : RD-Kelsey
 * @description 评论-业务逻辑层-实现
 * @date 2020/6/13
 */

@Service
@Slf4j
public class CommentsServiceImpl implements CommentsService {

    @Resource
    private CommentsMapper commentsMapper;

    /**
     * 任意条件查询评论，不传值默认全查
     * (可选)允许的参数：
     * commentsId 评论id
     * content 评论内容
     * weibo.weiboId 评论所在的微博id
     *
     * @param comments 实体
     * @return 评论列表
     */
    @Override
    public List<Comments> getCommentsByCondition(Comments comments) {
        if (comments != null) {
            //按照需求的参数返回对应的评论
            List<Comments> localComments = commentsMapper.getCommentsByCondition(comments);
            for (Comments c : localComments) {
                if (c != null) {
                    return commentsMapper.getCommentsByCondition(comments);
                }
            }
            //如果没传参，全查
        } else {
            return commentsMapper.getCommentsByCondition(null);
        }
        //其他情况
        return null;
    }

    /**
     * 发表评论
     *
     * @param comments 实体
     * @return true | false 是否成功
     */
    @Override
    public boolean addComments(Comments comments) {
        if (comments.getWeibo() != null && comments.getWeibo().getWeiboId() != null
                && comments.getContent() != null && !comments.getContent().equals("")) {
            //评论时间
            comments.setDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            //获取评论人id
            Long userId = Objects.requireNonNull(JwtTokenUtil.getUser()).getUserId();
            comments.setUserId(userId);
            return commentsMapper.addComments(comments);
        }
        return false;
    }

    /**
     * 删除评论
     *
     * @param commentsId 评论id
     * @return true | false 是否成功
     */
    @Override
    public boolean deleteComments(Long commentsId) {
        //查询是否有这条评论
        Comments comments = commentsMapper.getById(commentsId);
        if (comments != null) {
            return commentsMapper.deleteComments(commentsId);
        }
        return false;
    }

    /**
     * id单查
     *
     * @param commentsId 评论id
     * @return 评论
     */
    @Override
    public Comments getById(Long commentsId) {
        return commentsMapper.getById(commentsId);
    }
}
